/*************************************************
Name : NewCaseWebFormController
Created By : dthekumparampil
Created Date : Feb 1, 2013
Description :   Controller for Web-to-Case. 
                The web page picklist values depends on the source from which the call is made to this page. 
                If coming from mywest, the controller pulls the parameters from url and populates the fields in the form.
                Contains basic field checks.
******************************
Modified By : dthekumparampil
Modified Date : Feb 21, 2013
Modification :  Case Origin value depends on Source.
*************************************************/
/******************************
Modified By : suneetha
Modified Date : Feb 19, 2013
                Feb 20, 2013
                Feb 21, 2013
Modification : For mutiple File Attachment
*************************************************/
public without sharing class NewCaseWebFormController {
    
    public String attFileName1 {get;set;}
    public integer attFileSize1 {get;set;}
    public transient blob attFileContent1 {get;set;}
    
    public String attFileName2 {get;set;}
    public integer attFileSize2 {get;set;}
    public transient blob attFileContent2 {get;set;}
    
    public String attFileName3 {get;set;}
    public integer attFileSize3 {get;set;}
    public transient blob attFileContent3 {get;set;}
    
        
 // transient  List<Attachment> AttachmentstoInsert=new List<Attachment>();   
   public boolean secureWebFlag {get;set;}
   public boolean boolCaseSubmitted {get;set;}
   public boolean contactPhoneFlag {get; set;}
   public boolean newattachflg{get; set;} 
   
   
   //Added by Kalyani
    public Boolean checkbox01 {get; set;}
    //end by Kalyani
   // Added  By  suneetha feb 19 2013 For handle multiple attachemetns
  
  
    // list of new attachments to add
    public    List<Attachment> newAttachments {get; set;}
    
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String phone {get; set;}
    public String modeOfContact {get; set;}
    public String reasonForContact {get; set;}
    public String country {get; set;}
    public String state {get; set;}
    public String messageBody {get; set;}
    public String accountId {get;set;}
    private String currentURL;
    public String strReasonParameter='';
    public String strSourceParameter='';
    public String strLeadSource = '';
    public String strLeadSourceDetail ='';
    public String strRFISection = '';
    public String source = '';
    public String xml_Content = '';  
    public boolean attach1; 
    public boolean renderVantagePixel{get;set;}
    public boolean renderQuinStreetPixel{get;set;} 
        
        
    /****Constructor: If request is coming from 'https://' and contains parameter 'firstName' with value,
    then the firstName, lastName, email is searched in Account and Lead for match. If exact match found, 
    a case is created for the Lead/Account, else a new Lead is created with the credentials provided
    and a case is attached to it.****/
    
   // Added  By  suneetha feb 20 2013
    // public  List<integer>  filesize  {get; set;}
    
   //public Integer filesize1{get; set;}
   //  public Integer filesize2{get; set;}
    //  public Integer filesize3{get; set;}

        
public static void ErrorMessage(string message)
{       
  ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,message ));
}
      

        
public static void Debug(string message)
{
  // ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.INFO, 'webform'+'-'+ message));
       
}


    /** Save attachments *** Dinu 26 feb 2013 **/
    boolean saveAttachments(Case newCase){
        
        List<Attachment> attachmentsToInsert = new List<Attachment>();
        
        if(attFileContent1!=null){
            Attachment att1 = new Attachment(parentId=newCase.id, name=attFileName1, body=attFileContent1);
            attachmentsToInsert.add(att1);
            attFileContent1 = null;
            attFileSize1 = null;
            attFileName1 = null;
        }
        if(attFileContent2!=null){
            Attachment att2 = new Attachment(parentId=newCase.id, name=attFileName2, body=attFileContent2);
            attachmentsToInsert.add(att2);
            attFileContent2 = null;
            attFileSize2 = null;
            attFileName2 = null;
        }
        if(attFileContent3!=null){
            Attachment att3 = new Attachment(parentId=newCase.id, name=attFileName3, body=attFileContent3);
            attachmentsToInsert.add(att3);
            attFileContent3 = null;
            attFileSize3 = null;
            attFileName3 = null;
        }
        try{
            insert attachmentsToInsert;
        }
        catch(exception e){
            system.debug('error in attaching'+e.getmessage());
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR, 'problem with attachment'));
          //  System.Assert(e.getmessage());
            attachmentsToInsert=null;
            return false;
        }
        attachmentsToInsert=null;
        return true;    
    }



 
        public void DeleteAttach1() //changed the return type from PageReference to Void - dinu 26 Feb 2013
        {  
         try
         {
                /*Added by Dinu 26 feb 2013*/
                attFileContent1 = null;
                attFileSize1 = null;
                attFileName1 = null;
               
             /*Attach() ;
             Attachment att =new Attachment();
             newAttachments[0]=att;
             */ //Commented by Dinu 26 Feb 2013 
             }
              catch(VisualforceException ex)
         {  
          // ErrorMessage('I am gere'+ex.getmessage());
         }
             //return null;
        }
        public void DeleteAttach2() //changed the return type from PageReference to Void - dinu 26 Feb 2013
        {
                /*Added by Dinu 26 feb 2013*/
                attFileContent2 = null;
                attFileSize2 = null;
                attFileName2 = null;
             /*Attach();
             Attachment att =new Attachment();
             newAttachments[1]=att;
             return null;*/ //Commented by Dinu 26 Feb 2013 
             
        }
        public void DeleteAttach3() //changed the return type from PageReference to Void - dinu 26 Feb 2013
        {
                /*Added by Dinu 26 feb 2013*/
                attFileContent3 = null;
                attFileSize3 = null;
                attFileName3 = null;
             /*Attach();   
              Attachment att =new Attachment();
             newAttachments[2]=att; 
             return null;*/ //Commented by Dinu 26 Feb 2013 
         }
        
    
public void DefaultSettings()
{   
        try
        {
        
                newAttachments=new List<Attachment>{new Attachment()};
                for(integer i=1;i<3;i++)        
                newAttachments.add(new Attachment());
                
              
          
        }         
         catch (Dmlexception ex)
        {
           ErrorMessage(ex.getmessage());
                     
        }     
}
    // Ended   By  suneetha feb 20 2013 
    
    
public NewCaseWebFormController()
{
    
        //added By  suneetha feb 19 2013 For handle multiple attachemetns
         DefaultSettings();
        //Ended By  suneetha feb 19 2013 For handle multiple attachemetns
        
         boolCaseSubmitted = false;
         
        // Read the parameters and get them into readable format 
        for (String thisKey : ApexPages.currentPage().getParameters().keySet()){
            xml_Content += thisKey + ' :: ' + ApexPages.currentPage().getParameters().get(thisKey) + '\n';        
        }       
        
        
        // Encloding XML content        
        xml_Content = EncodingUtil.urlDecode(xml_Content, 'UTF-8');
        
            /*Message__C objMessage = new Message__C();
            objMessage.Description__c = xml_Content;
            objMessage.CreatedTime__c = system.now();
            try{
                insert objMessage;
            }catch(Exception e){
                
            }*/
            if(ApexPages.currentPage().getParameters().containsKey('Reason'))
                strReasonParameter = ApexPages.currentPage().getParameters().get('Reason');
            else
                strReasonParameter = '';
                
            if(ApexPages.currentPage().getParameters().containsKey('Source'))
                strSourceParameter = ApexPages.currentPage().getParameters().get('Source');
            else
                strSourceParameter = '';
            
            
            
            // parsing the Name tag from the XML
            if( xml_Content.indexof('<NAME>') > 0)
                source = xml_Content.substring(xml_Content.indexof('<NAME>')+6, xml_Content.indexof('</NAME>'));
            
            if( source.contains('MyWest')){
                firstName=xml_Content.substring(xml_Content.indexof('<GIVEN>')+7, xml_Content.indexof('</GIVEN>'));
                lastName=xml_Content.substring(xml_Content.indexof('<FAMILY>')+8, xml_Content.indexof('</FAMILY>'));
                email = xml_Content.substring(xml_Content.indexof('<EMAIL>')+7, xml_Content.indexof('</EMAIL>'));
                accountId = xml_Content.substring(xml_Content.indexof('<ID>')+4, xml_Content.indexof('</ID>'));
                secureWebFlag = true;
                //messageBody = accountId + ':   :'+source;
             }else if(strSourceParameter=='MyWest'){
                source = 'MyWest';
                secureWebFlag = true;
             }else{
                source = 'West.edu';
                secureWebFlag = false;
             }
             
             
            if(!secureWebFlag){
                if(ApexPages.currentPage().getParameters().containsKey('Type'))
                    strLeadSource = ApexPages.currentPage().getParameters().get('Type');
                else
                    strLeadSource = '';
                if(ApexPages.currentPage().getParameters().containsKey('RFICampaign'))
                    strLeadSourceDetail = ApexPages.currentPage().getParameters().get('RFICampaign');
                else
                    strLeadSourceDetail = '';
                
                if(ApexPages.currentPage().getParameters().containsKey('Section'))
                    strRFISection = ApexPages.currentPage().getParameters().get('Section');
                else
                    strRFISection = '';
                    
                if(strLeadSource=='' && strLeadSourceDetail=='' && strRFISection ==''){
                    strLeadSource='INET';
                    strLeadSourceDetail = 'Request Info';
                    strRFISection = 'west.edu';
                }
            }
             
            checkbox01 = true; 
            
            //Digital Media Pixels tracking code
            renderVantagePixel = false;
            renderQuinStreetPixel = false;
            west_case_management_utils__c objVantageRFICodeUtil = west_case_management_utils__c.getValues('Vantage');
            if(objVantageRFICodeUtil!=null){
                String[] strRFICampaignCodeValues = objVantageRFICodeUtil.Value__c.split('~',-1);   
                if(strRFICampaignCodeValues.size()>0){
                    for(integer index=0;index<strRFICampaignCodeValues.size();index++){
                        if(strRFICampaignCodeValues.get(index)==strLeadSourceDetail){
                            renderVantagePixel = true;
                        }
                    }
                }
            }
            if(!renderVantagePixel){
                west_case_management_utils__c objQuinStreetRFICodeUtil = west_case_management_utils__c.getValues('QuinStreet');
                if(objQuinStreetRFICodeUtil!=null){
                    String[] strRFICampaignCodeValues = objQuinStreetRFICodeUtil.Value__c.split('~',-1);    
                    if(strRFICampaignCodeValues.size()>0){
                        for(integer index=0;index<strRFICampaignCodeValues.size();index++){
                            if(strRFICampaignCodeValues.get(index)==strLeadSourceDetail){
                                renderQuinStreetPixel = true;
                            }
                        }
                    }
                }
            }
                
            
             
        
}
    
public String[] StateList = new String[] {'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Louisiana', 'Maine', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'West Virginia', 'Wisconsin', 'Wyoming' };
  
public List<SelectOption> getstates(){  
            List<SelectOption> picklistValues = new List<SelectOption>();
            picklistValues.add(new SelectOption('','Select State'));
            for (Integer i=0;i<StateList.size();i++)
              {
            picklistValues.add(new SelectOption(StateList[i],StateList[i]));
            }
            return picklistValues;        
}    
    /****Method to populate the reason For Conta ct PickList ****/
public List<SelectOption> getReasonForContactOptions(){
            
        list <West_Webform_Picklist__c> picklistValues;
        list <SelectOption> options = new list<SelectOption>();
        
        if(source.contains('MyWest')){
                picklistValues = [select Picklist_Value__c, URL_Mode__c from West_Webform_Picklist__c where URL_Mode__c='Secure' and Reason_Parameter__c=:strReasonParameter and Picklist_Value__c!='other' order  by  Picklist_Value__c];     
        }
        else{
                picklistValues = [select Picklist_Value__c, URL_Mode__c from West_Webform_Picklist__c where URL_Mode__c='Unsecure' and Reason_Parameter__c=:strReasonParameter  and Picklist_Value__c!='other'  order  by  Picklist_Value__c];
        }
        
        
        for(integer index=0; index<picklistValues.size(); index++){
                options.add(new SelectOption(picklistValues[index].Picklist_Value__c,picklistValues[index].Picklist_Value__c));
        }
        
        if(picklistValues.size()==0){
           // options.add(new SelectOption('Other','Other'));
        }
        options.add(new SelectOption('Other','Other'));
        return options;
}
        
        
   //****Method to populate the Mode of Contact PickList  ****/
    public List<SelectOption> getModeOfContactOptions(){
            
        list <SelectOption> options = new list<SelectOption>();
        
        options.add(new SelectOption('Email','Email'));
        options.add(new SelectOption('Phone','Phone'));
        return options; 
    }
    
       
        
    
     // ended  suneetha feb 21 2013  
      /****Method to Save ****/
    public Pagereference Save(){

       try{
                integer size = 1000000;
            //system.debug('the size are >>>>:'+attFileContent1.size()+'  and  '+attFileContent2.size());
            //return null;
            //system.debug('after null');
            if(attFileContent1!=null){
                if(attFileContent1.size()>size){
                    system.debug('inside file 1');
                    attFileContent1 = null;
                    attFileSize1 = null;
                    attFileName1 = null;
                    attFileContent2 = null;
                    attFileSize2 = null;
                    attFileName2 = null;
                    attFileContent3 = null;
                    attFileSize3 = null;
                    attFileName3 = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Attachment 1 exceeds the limit of 1MB'));
                    return null;
                }
            }
            if(attFileContent2!=null){
                if(attFileContent2.size()>size){
                    system.debug('inside file 2');
                    attFileContent2 = null;
                    attFileSize2 = null;
                    attFileName2 = null;
                    attFileContent1 = null;
                    attFileSize1 = null;
                    attFileName1 = null;
                    attFileContent3 = null;
                    attFileSize3 = null;
                    attFileName3 = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Attachment 2 exceeds the limit of 1MB'));
                    return null;
                }
            }
            if(attFileContent3!=null){
                if(attFileContent3.size()>size){
                    system.debug('inside file 3');
                    attFileContent3 = null;
                    attFileSize3 = null;
                    attFileName3 = null;
                    attFileContent1 = null;
                    attFileSize1 = null;
                    attFileName1 = null;
                    attFileContent2 = null;
                    attFileSize2 = null;
                    attFileName2 = null;
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Attachment 3 exceeds the limit of 1MB'));
                    return null;
                }
            }
       
        //Attach();
            
           // return  null;
         Debug('IN Save');
        list<Account> accountInSalesforce;
        list<Lead> leadInSalesforce;
        String ErrorMsg ='';
        Integer i=0;
        String accountRecordType = Schema.Sobjecttype.Account.getRecordTypeInfosByName().get('West - Student Account').getRecordTypeId();
        String leadRecordType = Schema.Sobjecttype.Lead.getRecordTypeInfosByName().get('West - Prospective Student').getRecordTypeId();
        String caseRecordType = Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('West - Support').getRecordTypeId();
        
        system.debug('firstname= '+firstname);
        system.debug('lastName= '+lastName);
        system.debug('email= '+email);
        system.debug('messageBody= '+messageBody);
        system.debug('reasonForContact= '+reasonForContact);
        system.debug('modeOfContact= '+modeOfContact);
        system.debug('state= '+state);
        system.debug('country= '+country);
       // system.debug('attachmentFilename= '+attachmentFilename);  // Done  By  suneetha feb 19 2013 
        
        
        /*Checking for mandatory fields*/
     /*   if(firstName==null || firstName.length()<1 || lastName==null || lastName.length()<1 || messageBody==null ||  messageBody.length()<1  || reasonForContact=='' || modeOfContact==''){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'FirstName, LastName, Mode Of Contact, Reason for Contact and Comments are  Mandatory Fields'));
                return null;
        } */ //Commented by Kalyani - handled in Web page
       if(firstName==null || firstName.length()<1){
        i+=1;
        if (i>1) ErrorMsg= ErrorMsg + ', '; 
        ErrorMsg = ErrorMsg + 'First Name';
       } 
       if(lastName==null || lastName.length()<1){
                i+=1;
                if (i>1) ErrorMsg= ErrorMsg + ', '; 
        ErrorMsg = ErrorMsg + 'Last Name';
       }
       if(modeOfContact==''){
        i+=1;
        if (i>1) ErrorMsg= ErrorMsg + ', '; 
        ErrorMsg = ErrorMsg + 'Mode Of Contact';
       }
        if(modeOfContact=='Email' && (email=='' || email==null )){
           i+=1;
           if (i>1) ErrorMsg= ErrorMsg + ', '; 
           ErrorMsg = ErrorMsg + 'Email Address';                    
        }
        if(modeOfContact=='Phone' && (phone=='' || phone==null )){
              i+=1;
              if (i>1) ErrorMsg= ErrorMsg + ', '; 
           ErrorMsg = ErrorMsg + 'Phone Number';                         
        }
        if(!source.contains('MyWest')){
                if(State==null || State==''){
                  i+=1;
              if (i>1) ErrorMsg= ErrorMsg + ', '; 
                        ErrorMsg = ErrorMsg + 'State';    
                }       
        }
        if(reasonForContact==null || reasonForContact==''){
         i+=1;
              if (i>1) ErrorMsg= ErrorMsg + ', '; 
           ErrorMsg = ErrorMsg + 'Reason for contact';   
        }
        /*if(messageBody==null ||  messageBody.length()<1 ){
            i+=1;
            if (i>1) ErrorMsg= ErrorMsg + ', '; 
            ErrorMsg = ErrorMsg + 'Comments';   
        }*/
        if (i>0)
               {
                    if (i>1)
                    {
                         ErrorMsg= ErrorMsg+ ' are Mandatory Fields';
                    } 
                    else
                    {
                       ErrorMsg= ErrorMsg+ ' is Mandatory Field';
                       
                    }
                     
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));  
               }
   //  ErrorMsg = ErrorMsg +;   
     if(checkbox01==false){
        i+=1;
     // ErrorMsg = ErrorMsg + '\r\n' + 'You must agree that you may be contacted';
        System.debug(ErrorMsg);
        ErrorMsg = 'You must agree that you may be contacted';
        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));
     }
  //   ErrorMsg = ErrorMsg +'\r\n';  
     if(email.length()>1 && (!Pattern.matches('^[a-zA-Z]+[a-zA-Z0-9_.]*@[A-Za-z0-9.]+\\.[A-Za-z]+$', email))) {
        i+=1;
     // ErrorMsg = ErrorMsg + 'Email is in wrong format';
     ErrorMsg = 'Email is in wrong format';
     ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));
        }        
   //   ErrorMsg = ErrorMsg +'\r\n';  
    /*  if(email.length()>80){
        i+=1;
        //ErrorMsg = ErrorMsg + 'Email too long, It should NOT be greater than 80 characters long';
        ErrorMsg =  'Email too long, It should NOT be greater than 80 characters long';
         ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));
           }  */ 
    //   ErrorMsg = ErrorMsg + '\r\n';
        String formattedPhoneNumber='';
        if(phone!=null && phone.length()>0 && phone!=''){
            Phone=Phone.trim();
            DataFormatter formatter = new DataFormatter();
            formattedPhoneNumber = formatter.phoneFormatter(phone);
            if(formattedPhoneNumber=='Failed'){
                    formattedPhoneNumber='';
         //           ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid Phone number'));
          //          return null;
          i+=1;
         // ErrorMsg = ErrorMsg + 'Enter Valid Phone Num';
         ErrorMsg =  'Enter Valid Phone Num';
           ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));
            }
        }      
     if(i>0){
     // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, ErrorMsg));
                return null;
     }  
    /*   if(modeOfContact=='Email' && (email=='' || email==null )){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Email since Preferred mode of contact is Email'));
                return null;                    
        } *///Commented by Kalyani - handled in Web page
       //  ErrorMessage('step3');
        /*Check for Phone if mode of contact is phone*/
       /* if(modeOfContact=='Phone' && (phone=='' || phone==null )){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Phone number since Preferred mode of contact is Phone'));
                return null;                    
        }*/ //Commented by Kalyani - handled in Web page
            
        /*Check for email format */ //email!='' &&
      /*  if(!Pattern.matches('^[a-zA-Z]+[a-zA-Z0-9_.]*@[A-Za-z0-9.]+\\.[A-Za-z]+$', email)) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email is in wrong format'));
            return null;
        }*/ //Commented by Kalyani - handled in Web page
            
        /*Email size check*/
      /*  if(email.length()>80){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Email too long, It should NOT be greater than 80 characters long'));
            return null;
        } *///Commented by Kalyani - handled in Web page
       //  ErrorMessage('step4');
        /*if((State == null || State =='') && (reasonForContact=='Enrollment Information'|| reasonForContact =='Program Information')){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'State is Mandatory if you are requesting contact for Enrollment and Program Infromation'));
            return null;
        }*/
                
        /****Trimming all the Input strings****/
        FirstName=FirstName.trim();
        LastName=LastName.trim();
        if(Email!=null)
            Email=Email.trim();
        if(State!=null)
            State=State.trim();
        
        
        
        /****Formatting the Phone number to search in database****/
     //   String formattedPhoneNumber='';
     /*   if(phone!=null && phone.length()>0 && phone!=''){
            Phone=Phone.trim();
            DataFormatter formatter = new DataFormatter();
            formattedPhoneNumber = formatter.phoneFormatter(phone);
            if(formattedPhoneNumber=='Failed'){
                    formattedPhoneNumber='';
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Enter Valid Phone number'));
                    return null;
            }
        }*/ //Commented by Kalyani
         //ErrorMessage('step5');
        /**** Finding the correct CaseName based on the Reason For Contact or Mode of Contact****/
        String caseName = '';
        list <West_Webform_Picklist__c> lstPicklistValues;
        if(source.contains('MyWest')){
                lstPicklistValues = [select Picklist_Value__c, Case_Name__c from West_Webform_Picklist__c where URL_Mode__c='Secure' and Case_Name__c!= ''];     
        }
        else{
                lstPicklistValues = [select Picklist_Value__c, Case_Name__c from West_Webform_Picklist__c where URL_Mode__c='Unsecure' and Case_Name__c!= ''];
        }
        for(West_Webform_Picklist__c objPickListValue:lstPicklistValues){
            if(objPickListValue.Picklist_Value__c == reasonForContact){
                caseName= objPickListValue.Case_Name__c;
            }
        }
        
        if(caseName==''){
            if(modeOfContact == 'Phone'){
                caseName = 'Call Applicant/Student';     
            }
            else{
                    caseName = 'Email Applicant/Student';
            }   
        }
        
        /** In the below code, the firstname, lastname and email are searched in lead and account. 
        If a match is found, new case is created for the same, else a new lead and case are created. **/
        
        /****Checking for match in Account****/
        
        
        
        if(source.contains('MyWest') && accountId!= null && accountId !=''){
            accountInSalesforce = [select id from Account where Account_id__c = :accountId];
            System.debug('SOQL FIRED....'); 
        }else{
            accountInSalesforce = [select id from Account where IsPersonAccount=true AND FirstName=:firstName and 
        LastName=:lastName and (PersonEmail=:email OR Marketing_Email__pc=:email OR Other_Email_2__pc=:email OR 
        University_Email__pc=:email OR Personal_Email__pc=:email OR Work_Email__pc=:email OR Other_Email__pc=:email) AND RecordTypeId =: accountRecordType ];   
        }   
        
         // ErrorMessage('step6');
        /****If found, update existing Account record, create new Case with all the details ****/
        if(accountInSalesforce.size()>0){
                        
            /****Adding Savepoint in case of failure****/
            Savepoint accountSavepoint = Database.setSavepoint();
             //ErrorMessage('step7');
            /**** Case is created here ****/
            Case newCase = new Case(AccountId=accountInSalesforce[0].id,RecordTypeId=caseRecordType,
                    Case_Name__c=caseName, Subject=caseName, Description=messageBody);
                    //newCase.Origin = 'Web';//
                    if(source.contains('MyWest')){
                        newCase.Origin = 'MyWest';
                    }
                    else{
                        newCase.Origin = 'West.edu';
                    }
                    newCase.Subject = reasonForContact;
                    newCase.Description = 'Web form Origin: '+source+'\nStudent Id: '+accountID +'\nPrefered Mode of Contact: '+modeOfContact + '\nPhone: '+ phone +'\nEmail: '+email +'\nReason for Contact: '+reasonForContact +'\nComments: '+ messageBody;
           //  ErrorMessage('step7.1');
              try{
                    insert newCase;
                }
              catch(DmlException dmle){
                   Database.rollback(accountSavepoint);
                    System.Debug('in case create' + dmle.getMessage());
                   return null;
                  ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Unable to create Case'));
                   return null;
              }
               
                 // Added  By  suneetha feb 19 2013 
                 //if (saveattachment(newcase,accountSavepoint)==false) //commented by dinu 26 feb 2013
                 if(!saveAttachments(newCase)){
                     return null;
                 }
             
                  //end   suneetha feb 19 2013
            
            
            boolCaseSubmitted = true;
            return null;
        }
        else{
            // ErrorMessage('step8');
            /****Checking for match in Lead****/
            leadInSalesforce = [select id,Lead_Source_2__c,Lead_Source_Detail_2__c,RFI_Section_2__c from lead where FirstName =:FirstName and LastName=:LastName and (Personal_Email__c=:email OR Email=:email 
            OR Marketing_Email__c=:email OR Other_Email_2__c=:email OR Other_Email__c=:email OR Preferred_Email__c=:email 
            OR University_Email__c=:email OR work_Email__c=:email) AND RecordTypeId =: leadRecordType AND isConverted= false];

            /****If found, update existing Lead record and create a new Case.****/
            if(leadInSalesforce.size()>0){
                
                Savepoint leadSavepoint = Database.setSavepoint();
                
                /**** Case is created here ****/
                Case newCase = new Case(lead__c=leadInSalesforce[0].id,RecordTypeId=caseRecordType,
                        Case_Name__c=caseName);
                //newCase.Origin = 'Web';
                if(source == 'MyWest Test'){
                    newCase.Origin = 'MyWest';
                }
                else{
                    newCase.Origin = 'West.edu';
                }
                newCase.Subject = reasonForContact;
                newCase.Description = 'Web form Origin: '+source+'\nStudent Id: '+accountID +'\nPrefered Mode of Contact: '+modeOfContact + '\nPhone: '+ phone +'\nEmail: '+email +'\nReason for Contact: '+reasonForContact +'\nComments: '+ messageBody;
               //  ErrorMessage('step8.1');
               /*if(strLeadSource=='INET' && strLeadSourceDetail=='INET' && strRFISection=='INET'){
                    if(leadInSalesforce[0].Lead_Source_2__c=='' && leadInSalesforce[0].Lead_Source_Detail_2__c=='' && leadInSalesforce[0].RFI_Section_2__c==''){
                        leadInSalesforce[0].Lead_Source_2__c = strLeadSource;
                        leadInSalesforce[0].Lead_Source_Detail_2__c = strLeadSourceDetail;
                        leadInSalesforce[0].RFI_Section_2__c = strRFISection;   
                    }
               }else{*/
                leadInSalesforce[0].Lead_Source_2__c = strLeadSource;
                leadInSalesforce[0].Lead_Source_Detail_2__c = strLeadSourceDetail;
                leadInSalesforce[0].RFI_Section_2__c = strRFISection;
                leadInSalesforce[0].RFI_Campaign_Code__c = strLeadSourceDetail;
               //}
               try{
                    insert newCase;
                    update leadInSalesforce[0];
               }
                catch(DmlException dmle){
                 Database.rollback(leadSavepoint);
                  ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Unable to create Case'));
                    return null;
               }
                
                  // Added  By  suneetha feb 19 2013                  
                 //if (saveattachment(newcase,leadSavepoint)==false)//commented by dinu 26 feb 2013
                if(!saveAttachments(newCase)){ 
                    return null;
                }
             
                 //comments ended  by  suneetha  feb 19 2013
                boolCaseSubmitted = true;
                
                return null;
            }
            else{
                
                // ErrorMessage('step9');
                /****If there is no lead or account matches, a new lead and associated case is created ****/
                Lead newLead = new Lead();
                newLead.FirstName = FirstName;
                newLead.LastName = LastName;
                newLead.Personal_Email__c = Email;
                if(State!=null && state != '')
                    newLead.State = State;
                else
                    newLead.state = 'Arizona';
                newLead.RecordTypeId = leadRecordType;
                newLead.Country = 'US';
                newLead.LeadSource = strLeadSource;
                newLead.lead_source_Detail__c = strLeadSourceDetail;
                newLead.RFI_Section__c = strRFISection;
                newLead.RFI_Campaign_Code__c = strLeadSourceDetail;

                if(formattedPhoneNumber.length()>0){
                    newLead.Home_Phone__c = formattedPhoneNumber;

                }
                
                Savepoint newleadSavepoint = Database.setSavepoint();
                           //  ErrorMessage('step9.1');
                try{
                    insert newLead;
                }
                catch (Dmlexception DmlE){
                    system.debug('DMLException while inserting'+dmlE.getmessage());
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Unable to create new Lead'));
                    return null;
                }
                /**** Case is created here and associated with the lead just created ****/
                Case newCase = new Case(lead__c=newLead.id,RecordTypeId=caseRecordType,
                        Case_Name__c=caseName);
                //newCase.Origin = 'Web';
                if(source == 'MyWest Test'){
                    newCase.Origin = 'MyWest';
                }
                else{
                    newCase.Origin = 'West.edu';
                }
                newCase.Subject = reasonForContact;
                newCase.Description = 'Web form Origin: '+source+'\nStudent Id: '+accountID +'\nPrefered Mode of Contact: '+modeOfContact + '\nPhone: '+ phone +'\nEmail: '+email +'\nReason for Contact: '+reasonForContact +'\nComments: '+ messageBody;
                
                try{
                    insert newCase;
                }
                catch(DmlException dmle){
                    Database.rollback(newleadSavepoint);
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Unable to create Case'));
                    return null;
                }
                
                
                 // Added  By  suneetha feb 19 2013                  
                //if (saveattachment(newcase,newleadSavepoint)==false)//commented by dinu 26 feb 2013 
                if(!saveAttachments(newCase)){
                    return null;
                }
                 // ended  By  suneetha feb 19 2013  
                boolCaseSubmitted = true;
                
                return null;
            }
        }
   }
 
    catch(Exception ex)
   {
       ErrorMessage(ex.getmessage());
                  return null;  
   }
      return null;
  }
    public PageReference goToWest(){
        PageReference newPage = new Pagereference('http://www.west.edu/');
        newPage.setRedirect(true);
        return newPage;
    }
}